#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <stdexcept>

// 目标接口：现代播放器
class IAudioPlayer 
{
public:
    virtual void Play(const std::string& filename) = 0;
    virtual ~IAudioPlayer() = default;
};

// 被适配者1：旧版MP3播放器
class OldMp3Player 
{
public:
    void PlayMp3(const std::string& filename)
    {
        std::cout << "使用旧版MP3播放器播放：" << filename << std::endl;
    }
};

// 被适配者2：旧版WAV播放器
class OldWavPlayer 
{
public:
    void PlayWav(const std::string& filename)
    {
        std::cout << "使用旧版WAV播放器播放：" << filename << std::endl;
    }
};

// 适配器1：将旧版MP3播放器适配为现代播放器
class Mp3Adapter : public IAudioPlayer 
{
private:
    OldMp3Player oldPlayer;
public:
    void Play(const std::string& filename) override 
    {
        if (filename.size() < 4 || filename.substr(filename.size() - 4) != ".mp3") 
        {
            throw std::invalid_argument("文件格式错误：只支持.mp3文件");
        }
        oldPlayer.PlayMp3(filename);
    }
};

// 适配器2：将旧版WAV播放器适配为现代播放器
class WavAdapter : public IAudioPlayer 
{
private:
    OldWavPlayer oldPlayer;
public:
    void Play(const std::string& filename) override 
    {
        if (filename.size() < 4 || filename.substr(filename.size() - 4) != ".wav") 
        {
            throw std::invalid_argument("文件格式错误：只支持.wav文件");
        }
        oldPlayer.PlayWav(filename);
    }
};

// 客户端工厂：根据文件类型选择合适的适配器
class AudioPlayerFactory 
{
public:
    static std::unique_ptr<IAudioPlayer> CreatePlayer(const std::string& filename)
    {
        if (filename.size() >= 4)
        {
            std::string ext = filename.substr(filename.size() - 4);
            if (ext == ".mp3")
            {
                return std::make_unique<Mp3Adapter>();
            }
            else if (ext == ".wav") 
            {
                return std::make_unique<WavAdapter>();
            }
        }
        throw std::invalid_argument("不支持的音频格式");
    }
};
